import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart' as GetX;
import 'package:image_picker/image_picker.dart';
import 'package:nft_shop/net/service_repository.dart';
import 'package:nft_shop/widgets/image.dart';
import 'package:nft_shop/widgets/load_image.dart';

class SelectedImage extends StatefulWidget {
  Function(String url)? determineBack;
  String? url;
  SelectedImage({this.url,this.determineBack});

  @override
  _SelectedImageState createState() => _SelectedImageState();
}

class _SelectedImageState extends State<SelectedImage> {
  //实例化选择图片
  final ImagePicker picker = new ImagePicker();
//用户本地图片
  File? _userImage;//存放获取到的本地路径

  //异步吊起相机拍摄新照片方法
  Future _getCameraImage() async {
    final cameraImages = await picker.getImage(source: ImageSource.camera);
    if (mounted) {
      setState(() {
        //拍摄照片不为空
        if (cameraImages != null) {
          _userImage = File(cameraImages.path);
          _upLoadImage(_userImage!);
          print('你选择的路径是：${_userImage.toString()}');
          //图片为空
        } else {
          print('没有照片可以选择');
        }
      });
    }
  }
  Future _getImage() async {
    //选择相册
    final pickerImages = await picker.getImage(source: ImageSource.gallery);
    if(mounted){
      setState(() {
        if(pickerImages != null){
          _userImage = File(pickerImages.path);
          _upLoadImage(_userImage!);
          print('你选择的本地路径是：${_userImage.toString()}');
        }else{
          print('没有照片可以选择');
        }
      });
    }
  }

  //图片提交
  _upLoadImage(File image) async {
    String path = image.path;
    String name = path.substring(path.lastIndexOf("/") +1, path.length);

    FormData formdata = FormData.fromMap({
      "file": await MultipartFile.fromFileSync(path,filename:name,),
    });
    EasyLoading.show(status: "正在加载...");
    try{
      var url = await ServiceRepository.fileUpload(formdata);
      EasyLoading.dismiss();
      if(url.length != 0){
        setState(() {
          widget.url = url;
        });
        widget.determineBack!(url);

        EasyLoading.showToast("上传成功");
      }
    }catch (e, s) {
      EasyLoading.showToast("上传失败");
    }
  }
  //弹出
  void _showHintDialog(BuildContext contexts) {
    showModalBottomSheet<void>(
      context: context,

      /// 禁止拖动关闭
      enableDrag: true,

      /// 使用true则高度不受16分之9的最高限制
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      barrierColor: Color(0x80000000),
      builder: (_) => Container(
        color: Colors.transparent,
        height: 190,
        width: 120,
        padding: EdgeInsets.symmetric(horizontal: 16),
        child: Column(
          children: [
            _buildItem(
                title: "拍摄",
                border: BorderRadius.only(
                    topLeft: Radius.circular(4), topRight: Radius.circular(4)),
                onTap: (){
                  GetX.Get.back();
                  _getCameraImage();}
            ),
            Container(
              color: Color(0xFFF5F5F5),
              height: 1,
              width: double.infinity,
            ),
            _buildItem(
                title: "从相册选择",
                border: BorderRadius.only(
                    bottomLeft: Radius.circular(4),
                    bottomRight: Radius.circular(4)),
                onTap: (){
                  GetX.Get.back();
                  _getImage();}
            ),
            SizedBox(
              height: 10,
            ),
            _buildItem(title: "取消", border: BorderRadius.circular(4),onTap: (){
              GetX.Get.back();
            }),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {

    Widget image = ClipOval(
      child: WrapperImage(
        url: widget.url!,
        height: 40,
        width: 40,
        placeholder: LoadAssetImage(
          "header_img",
          width: 40,
          height: 40,
        ),
      ),
      // child: LoadImage(
      //   widget.url!,
      //   width: 40,
      //   height: 40,
      //   holderImg: "my/header",
      // ),
    );

    return Semantics(
      label: '选择图片',
      hint: '跳转相册选择图片',
      child: InkWell(
        borderRadius: BorderRadius.circular(16.0),
        onTap: (){_showHintDialog(context);},
        child: image,
      ),
    );
  }

  //item
  Widget _buildItem(
      {required String title,
      BorderRadiusGeometry? border,
      GestureTapCallback? onTap}) {
    return InkWell(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: border,
        ),
        height: 50,
        child: Center(
            child: Text(
          title,
          style: TextStyle(
              fontWeight: FontWeight.w600,
              fontSize: 16,
              color: Color(0xFF2F73FD)),
        )),
      ),
    );
  }
}
